<?php

declare (strict_types = 1);



namespace app\stores\middleware;

//验证小程序的过期时间

use app\common\logic\TokenLogic;

use app\common\model\ShopModel;

use app\common\model\ShopDetailModel;
use app\stores\model\member\MemberLevelModel;

class MiniappCheck

{

    use \app\BaseTrait;

    /**

     * 处理请求

     *  验证是否登录是否正确的中间件

     * @param \think\Request $request

     * @param \Closure       $next

     * @return Response

     */

    public function handle($request, \Closure $next)

    {

        $shopId = $request->param('shop_id/d');

        if(empty($shopId)){

            return $this->error('小程序不存在或已经被删除');

        }

        $miniapp = cache('miniapp_'.$shopId);

        if(empty($miniapp)){

            $miniappApp = ShopModel::find($shopId);

            if(null === $miniappApp){

                return $this->error('小程序不存在或已经被删除');

            }

            if(null === $shopDetail = ShopDetailModel::find($shopId)){

                return $this->error('店铺信息未配置');

            }

            $miniapp = [

                'name'=>$miniappApp->name,

                'logo'=>$shopDetail->logo,

                'business_hours'=>$shopDetail->business_hours,

                'tel'=>$shopDetail->tel,

                'address'=>$shopDetail->address,

                'lng'=>$shopDetail->lng,

                'lat'=>$shopDetail->lat,

                'door_license_plate' => $shopDetail->door_license_plate,

                'info'  => $shopDetail->info,

                'expire_time'       => $miniappApp->expire_time,

                'white_list_open' =>$shopDetail->white_list_open,

                'default_send_type' =>$miniappApp->default_send_type


            ];

            cache('miniapp_'.$shopId,$miniapp,3600);

        }

        

        if($miniapp['expire_time'] < $request->time()){

            return $this->error('小程序已经过期了');

        }

        $request->shopId = $shopId;

        $request->miniapp = $miniapp;

            

        $token = $request->param('auth_token');

        if(empty($token)){ //需要给MEMBERID重置 

            $request->memberId = 0;

        }else{

            $datas = TokenLogic::getMiniMemberId($token);

            if($datas != false){

                $request->memberId = $datas;

            }else{ 

                $request->memberId = 0;

            }

        }

        return $next($request);

    }


}

